package com.h3bpm.web.msg.util;

import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.Map;

/**
 * java 与 json 互相转换工具类
 * @author Administrator
 *
 */

public class JSONUtils {

    public static <T> T toObject(String jsonStr, Class<T> cls) {
        String json = jsonStr;

        T obj = null;
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            obj = objectMapper.readValue(
                    json, cls);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj;
    }

    public static String toJson(Object obj) {
        ObjectMapper objectMapper = null;
        JsonGenerator jsonGenerator = null;
        String result = "";
        try {
            objectMapper = new ObjectMapper();
            jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(System.out, JsonEncoding.UTF8);
            result = objectMapper.writeValueAsString(obj);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    private static ObjectMapper objectMapper = new ObjectMapper();
    private static JsonFactory jsonFactory = new JsonFactory();

    /**
     * json字符串转Map
     * 2015年4月3日上午10:41:25
     * auther:shijing
     *
     * @param jsonStr
     * @return
     * @throws
     */
    public static Map<String, Object> parseMap(String jsonStr) throws IOException {
        Map<String, Object> map = objectMapper.readValue(jsonStr, Map.class);
        return map;
    }

    }



